<?php
namespace classlib\loger;
class file extends log_abstract {
	/**
	 * 定义文件的结构
	 * @var string $file
	 */
	private $file;
	
    /**
     * 文件日志构造函数
     * @param string $path  LOG存放路径
     * @param string $level 日志记录开启等级
     */
    public function __construct($param) {
    	$this->file = isset($param['path'])? $param['path']:'log/';
    	$this->file.= date('Ym').'/';
    	if(!is_dir($this->file)) {
        	mkdir($this->file, 0775, true);
        }
        @chmod($this->file, 0777);
		$this->level   = isset($param['lv'])? intval($param['lv']):self::LOG_DEBUG;
		$this->channal = array();
    }
    
    /**
     * 记录日志操作
     * @param string $msg 日志数据(数组)
     * @param int    $lv  日志错误等级 
     * @param string $prefix 日志文件前缀
     * @return boolean 返回是否记录成功
     */
    public function write($msg, $lv=log_abstract::LOG_ERR, $prefix='web') {
    	if($lv > $this->level) {
    		return;
    	}
    	$name  = sprintf('%s_%s.log', $prefix, date('Ymd'));
    	if (!isset($this->channal[$name])) {
    		$this->channal[$name] = @fopen($this->file.$name, "a+");
    	}
		//只验证默认的ACL
		$user  = '匿名';
		$msg   = str_replace(array("\n", "\r"), '', $msg);
		$uri   = (!isset($_SERVER['REQUEST_URI']))? '匿名来源':$_SERVER['REQUEST_URI'];
		$data  = array(date('H:i:s'), $user, $msg, $uri, $lv, \classlib\core\get_ip());
		fwrite($this->channal[$name], implode(';', $data)."\r\n");
    }
     
    /**
     * 析构的时候回收文件句柄
     * @return void
     */
    public function __destruct() {
    	if ($this->channal) {
    		foreach ($this->channal as $fp) {
    			fclose($fp);
    		}
    		$this->channal = null;
    	}
    }
}